import { Context } from "koa";
import multer from "@koa/multer";
import { ImageService } from "../services/image.service";
import { ImageUploadResponse } from "../dtos/image.dto";

// 配置multer
const storage = multer.memoryStorage();
const upload = multer({
  storage,
  limits: {
    fileSize: 25 * 1024 * 1024, // 25MB限制
  },
  fileFilter: (
    req: any,
    file: Express.Multer.File,
    cb: (error: Error | null, acceptFile: boolean) => void
  ) => {
    // 只允许图片文件
    if (file.mimetype.startsWith("image/")) {
      cb(null, true);
    } else {
      cb(new Error("只支持图片文件"), false);
    }
  },
});

export class ImageController {
  /**
   * 上传菜品图片
   */
  public static upload = upload.single("image");

  /**
   * 处理图片上传
   */
  public static async uploadImage(ctx: Context): Promise<void> {
    try {
      if (!ctx.file) {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: "请选择要上传的图片",
        };
        return;
      }

      const { buffer, originalname } = ctx.file;

      // 处理图片
      const result: ImageUploadResponse =
        await ImageService.uploadAndProcessImage(buffer, originalname);

      ctx.status = 200;
      ctx.body = {
        code: 200,
        message: "图片上传成功",
        data: result,
      };
    } catch (error) {
      console.error("图片上传失败:", error);

      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: error instanceof Error ? error.message : "图片上传失败",
      };
    }
  }

  /**
   * 错误处理中间件
   */
  public static async handleUploadError(
    ctx: Context,
    next: () => Promise<any>
  ): Promise<void> {
    try {
      await next();
    } catch (error: unknown) {
      // 检查是否为multer错误
      const err = error as any;
      if (
        err &&
        err.code &&
        typeof err.code === "string" &&
        err.code.startsWith("LIMIT_")
      ) {
        if (err.code === "LIMIT_FILE_SIZE") {
          ctx.status = 400;
          ctx.body = {
            code: 400,
            message: "图片大小不能超过25MB",
          };
          return;
        }
      }

      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: error instanceof Error ? error.message : "文件上传处理失败",
      };
    }
  }
}
